/*
Source : https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
Author : nflush@outlook.com
Date   : 2016-07-08
*/

/*
105. Construct Binary Tree from Preorder and Inorder Traversal

    Total Accepted: 68247
    Total Submissions: 233098
    Difficulty: Medium

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Subscribe to see which companies asked this question
*/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 // 52ms
class Solution {
private:
    TreeNode* buildTreeS(vector<int>& preorder, vector<int>& inorder, int low, int high, int &pindex) {
        if (low == high) return NULL;
        TreeNode* root = new TreeNode(preorder[pindex]);
        int mid;
        for (mid = low;mid < high;mid++){
            if(inorder[mid] == preorder[pindex]) break;
        }
        pindex++;
        root->left = buildTreeS(preorder, inorder, low, mid, pindex);
        root->right = buildTreeS(preorder, inorder, mid + 1, high, pindex);
        return root;
    }
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int pindex = 0;
        return buildTreeS(preorder, inorder, 0, preorder.size(), pindex);
    }
};


